#include "datamanagedialog.h"
#include "MessageBox.h"
#include "models/operatelogmodel.h"
#include "qwindow.h"
#include "ui_datamanagedialog.h"
#include "robotdialog.h"
#include"models/robotlist.h"
#include"QPainter"
#include <QMouseEvent>
#include <QScrollBar>
#include <QStringListModel>
#include"MessageBox.h"
#include <QScroller>

RobotDelegate::RobotDelegate(QObject *parent): QStyledItemDelegate(parent) {}

void RobotDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 保存画笔状态
    painter->save();
    
    // 绘制复选框图标
    QIcon checkIcon;
    bool isChecked = index.data(RobotList::CheckRole).toBool(); // 使用UserRole存储选中状态
    if (isChecked) {
        checkIcon = QIcon(":/images/check.png");
    } else {
        checkIcon = QIcon(":/images/uncheck.png");
    }
    
    // 复选框位置
    const int checkSize = int(20*g_xScale); // 复选框大小
    QRect checkRect = option.rect;
    //checkRect.setLeft(option.rect.left() + 10*g_xScale)); // 左边留出10像素边距
    checkRect.setWidth(checkSize);
    checkRect.setTop(option.rect.top() + (option.rect.height() - checkSize) / 2);
    checkRect.setHeight(checkSize);
    
    // 绘制复选框
    checkIcon.paint(painter, checkRect);
    
    // 文本区域需要右移，为复选框留出空间
    QRect textRect = option.rect;
    textRect.setLeft(checkRect.right() + int(10*g_xScale)); // 复选框右侧留出10像素间距
    textRect.setRight(option.widget->rect().width() - int(140*g_xScale)); // 为两个按钮预留空间
    
    // 绘制文本
    QFont f("微软雅黑");
    f.setPixelSize(int(20*g_xScale));
    painter->setFont(f);
    QString text = index.data(RobotList::NameRole).toString();
    QString elidedText = painter->fontMetrics().elidedText(text, Qt::ElideRight, textRect.width());
    painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, elidedText);

    // 绘制编辑和删除图标
    QIcon editIcon(":/images/edit.png");
    QIcon deleteIcon(":/images/delete.png");
    
    const int iconSize = int(40*g_xScale);
    QRect editIconRect = option.rect;
    editIconRect.setLeft(option.widget->rect().width() - int(120*g_xScale));
    editIconRect.setWidth(iconSize);
    editIconRect.setTop(option.rect.top() + (option.rect.height() - iconSize) / 2);
    editIconRect.setHeight(iconSize);

    QRect deleteIconRect = option.rect;
    deleteIconRect.setLeft(option.widget->rect().width() - int(70*g_xScale));
    deleteIconRect.setWidth(iconSize);
    deleteIconRect.setTop(option.rect.top() + (option.rect.height() - iconSize) / 2);
    deleteIconRect.setHeight(iconSize);

    editIcon.paint(painter, editIconRect);
    deleteIcon.paint(painter, deleteIconRect);
    
    painter->restore();
}

bool RobotDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if (event->type() == QEvent::MouseButtonRelease) {
        const QMouseEvent *mouseEvent = dynamic_cast<const QMouseEvent*>(event);
        if (!mouseEvent) return false;

        // 复选框区域
        const int checkSize = int(40*g_xScale);
        QRect checkRect = option.rect;
        checkRect.setLeft(option.rect.left());
        checkRect.setWidth(checkSize);
        checkRect.setTop(option.rect.top() + (option.rect.height() - checkSize) / 2+2);
        checkRect.setHeight(checkSize);

        // 编辑图标区域
        const int iconSize = int(40*g_xScale);
        QRect editIconRect = option.rect;
        editIconRect.setLeft(option.widget->rect().width() - int(120*g_xScale));
        editIconRect.setWidth(iconSize);
        editIconRect.setTop(option.rect.top() + (option.rect.height() - iconSize) / 2);
        editIconRect.setHeight(iconSize);

        // 删除图标区域
        QRect deleteIconRect = option.rect;
        deleteIconRect.setLeft(option.widget->rect().width() - int(70*g_xScale));
        deleteIconRect.setWidth(iconSize);
        deleteIconRect.setTop(option.rect.top() + (option.rect.height() - iconSize) / 2);
        deleteIconRect.setHeight(iconSize);

        RobotList * pRobotList = qobject_cast<RobotList*>(model);
        if (!pRobotList) return false;
        Robot * pRobot = pRobotList->getRobotByIndex(index.row());
        if (!pRobot) return false;

        if (checkRect.contains(mouseEvent->pos())) {
            // 处理复选框点击
            pRobotList->setCheckByIndex(index.row(),!index.data(RobotList::CheckRole).toBool());
            return true;
        } else if (editIconRect.contains(mouseEvent->pos())) {
            // 处理编辑图标点击
            RobotDialog dlg(pRobot, qobject_cast<QWidget*>(parent()));
            dlg.exec();
            return true;
        } else if (deleteIconRect.contains(mouseEvent->pos())) {
            // 处理删除图标点击
            if(question(qobject_cast<QWidget*>(parent()),tr("确定删除机器人\"%1\"吗？").arg(pRobot->strName())) == 0)
            {
                OPERATE_LOG("删除机器人："+pRobot->strName());
                pRobotList->removeByIndex(index.row());
            }
            return true;
        }
    }
    return false;
}

QSize RobotDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option)
    Q_UNUSED(index)
    return QSize(200, int(50*g_xScale));
}


DataManageDialog::DataManageDialog(QWidget *parent) :
    PopupDialog(parent),
    ui(new Ui::DataManageDialog)
{
    ui->setupUi(this);
    setModal(true);
    setupData();
    scaleWidgets(this,g_xScale,g_yScale);
}

void DataManageDialog::scaleWidgets(QWidget *widget, double xScale,double yScale)
{
    setFixedSize(int(widget->width() * xScale),int(widget->height() * yScale));
    for (QWidget * child : widget->findChildren<QWidget*>()) {
        QRect geom = child->geometry();
        if (qobject_cast<QScrollBar*>(child))
            child->setFixedWidth(int(geom.width() * xScale));
        else
        {
            int width = qMax(1, static_cast<int>(geom.width() * xScale));
            //当按钮高度比较大时使用y方向比例，当按钮比较小时使用x比例，防止按钮被压扁
            int height = qMax(1, static_cast<int>((geom.height() == geom.width() ? int(geom.height() * xScale) : int(geom.height() * yScale))));
            child->setFixedSize(width,height);
            child->move(int(geom.left() * xScale),int(geom.top() * yScale));
            QFont font = child->font();
            if(font.pixelSize()> 0)
                font.setPixelSize(int(font.pixelSize()*xScale));
            else if(font.pointSize()> 0)
                font.setPixelSize(int(font.pointSize()*xScale));
            child->setFont(font);
        }
    }
}

DataManageDialog::~DataManageDialog()
{
    delete ui;
}

void DataManageDialog::setupData()
{
    ui->robot_list->setModel(RobotList::getInstance());
    ui->robot_list->setItemDelegate(new RobotDelegate(this));
    ui->robot_list->setVerticalScrollMode(QListView::ScrollPerPixel);
    QScroller::grabGesture(ui->robot_list, QScroller::LeftMouseButtonGesture);
    ui->robot_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->robot_list->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}

void DataManageDialog::on_close_btn_clicked()
{
    reject();
}


void DataManageDialog::on_new_robot_btn_clicked()
{
    RobotDialog dlg(NULL,this);
    if(dlg.exec() == QDialog::Accepted) {
        // 获取最后一行索引
        QModelIndex lastIndex = RobotList::getInstance()->index(RobotList::getInstance()->getCount()-1);
        // 选中最后一行
        ui->robot_list->setCurrentIndex(lastIndex);
        // 滚动到最后一行
        ui->robot_list->scrollTo(lastIndex);
    }
}



void DataManageDialog::on_new_site_btn_clicked()
{
    warning(this,tr("训练场功能未实现"));
}



